package com.songcha.sakura.download.m3u8

import android.os.Parcel
import android.os.Parcelable
import com.songcha.sakura.download.base.DownloadTask
import com.songcha.sakura.download.base.TaskState

class M3u8DownloadTask(val m3u8Url:String, option: M3u8DownloadOption) : DownloadTask(m3u8Url,option) {

    var currentTsCount=0
    var totalTsCount=0

    constructor(parcel: Parcel) : this(
        parcel.readString()?:"",
        parcel.readParcelable(M3u8DownloadOption::class.java.classLoader)!!
    ) {

        url=parcel.readString()?:""
        id=parcel.readInt()
        tId=parcel.readLong()
        currentSize=parcel.readInt()
        fileSize=parcel.readInt()
        progress=parcel.readInt()
        state= parcel.readInt()?.let {
            when(it){
                TaskState.PRE.ordinal->{
                    return@let TaskState.PRE
                }
                TaskState.INITIALIZE.ordinal->{
                    return@let TaskState.INITIALIZE
                }
                TaskState.PAUSE.ordinal->{
                    return@let TaskState.PAUSE
                }
                TaskState.DOWNLOADING.ordinal->{
                    return@let TaskState.DOWNLOADING
                }
                TaskState.COMPLETED.ordinal->{
                    return@let TaskState.COMPLETED
                }
                TaskState.ERROR.ordinal->{
                    return@let TaskState.ERROR
                }

            }
            return@let TaskState.PRE
        }!!
        downloadDelegate=parcel.readParcelable(M3u8DownloadTask::class.java.classLoader)!!

        currentTsCount=parcel.readInt()
        totalTsCount=parcel.readInt()
    }

    override fun setProgress(){
        progress=((currentTsCount*1.0)/totalTsCount*100).toInt()
    }


    override fun writeToParcel(parcel: Parcel, flags: Int) {

        parcel.writeString(m3u8Url)
        parcel.writeParcelable(option, flags)

        parcel.writeString(url)
        parcel.writeInt(id)
        parcel.writeLong(tId)
        parcel.writeInt(currentSize)
        parcel.writeInt(fileSize)
        parcel.writeInt(progress)
        parcel.writeInt(state.ordinal)
        parcel.writeParcelable(downloadDelegate,flags)
        parcel.writeInt(currentTsCount)
        parcel.writeInt(totalTsCount)

    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<M3u8DownloadTask> {
        override fun createFromParcel(parcel: Parcel): M3u8DownloadTask {
            return M3u8DownloadTask(parcel)
        }

        override fun newArray(size: Int): Array<M3u8DownloadTask?> {
            return arrayOfNulls(size)
        }
    }


}